//
//  HomeViewModel.swift
//  WBDemo
//
//  Created by Meng on 17/2/15.
//  Copyright © 2017年 demo. All rights reserved.
//

import UIKit

class HomeViewModel: NSObject {
    
    var status: Status?
    
    var verified_image: UIImage?
    
    var mbrank_image: UIImage?
    
    var created_time: String?
    
    var source_text: String?
    
    var thumbnail_urls: [URL]?
    
    var bmiddle_urls: [URL]?
    
    var forward_text: String?
    
    init(status: Status) {
        
        self.status = status
        
        // 处理认证图片
        if let type = status.user?.verified_type {
            var name: String
            
            switch type {
            case 0:
                name = "avatar_vip"
            case 2, 3, 5:
                name = "avatar_enterprise_vip"
            case 220:
                name = "avatar_grassroot"
            default:
                name = ""
            }
            if name.characters.count > 0 {
                verified_image = UIImage(named: name)
            } else {
                verified_image = nil
            }
            
        }
        // 处理vip图片
        if let rank = status.user?.mbrank {
            
            if rank >= 1 && rank <= 6 {
                mbrank_image = UIImage(named: "common_icon_membership_level\(rank)")
            } else {
                mbrank_image = nil
            }
        }
        // 处理微博创建时间
        if let timeStr = status.created_at {
            // 转化为Date
            let createDate = Date.createDate(timeStr: timeStr, formatterStr: "EE MM dd HH:mm:ss Z yyyy")
            
            created_time = createDate.descriptionStr()
        }
        // 处理微博来源
        if let sourceStr = status.source as NSString?, sourceStr != "" {
            let startIndex = sourceStr.range(of: ">").location + 1
            let lenght = sourceStr.range(of: "<", options: .backwards).location - startIndex
            let rest = sourceStr.substring(with: NSMakeRange(startIndex, lenght))
            
            source_text = "来自 " + rest
        }
        // 处理转发微博正文
        if let forwardText = status.retweeted_status?.text {
            let name = status.retweeted_status?.user?.screen_name ?? ""
            forward_text = "@" + name + ": " + forwardText
        }
        // 处理微博配图URL
        if let urlStrs = (status.retweeted_status != nil) ? status.retweeted_status?.pic_urls : status.pic_urls {
            thumbnail_urls = [URL]()
            bmiddle_urls = [URL]()
            for dict in urlStrs {
                guard var urlStr = dict["thumbnail_pic"] as? String else {
                    continue
                }
                let url = URL(string: urlStr)!
                thumbnail_urls?.append(url)
                urlStr = urlStr.replacingOccurrences(of: "thumbnail", with: "bmiddle")
                let url2 = URL(string: urlStr)!
                bmiddle_urls?.append(url2)
            }
        }
    }
}
